import 'dart:io';
import 'package:appflutterhomeschool/api/api_service.dart';
import 'package:appflutterhomeschool/api/dio_utils.dart';
import 'package:appflutterhomeschool/common/common.dart';
import 'package:appflutterhomeschool/res/colors.dart';
import 'package:appflutterhomeschool/res/styles.dart';
import 'package:appflutterhomeschool/ui/dialogs/prompt_dialog_widgets.dart';
import 'package:appflutterhomeschool/ui/widgets/button_widget.dart';
import 'package:appflutterhomeschool/ui/widgets/my_app_bar.dart';
import 'package:appflutterhomeschool/ui/widgets/widgets.dart';
import 'package:appflutterhomeschool/utils/sp_util.dart';
import 'package:appflutterhomeschool/view_model/my/my_view_model.dart';
import 'package:appflutterhomeschool/view_model/my_app_view_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';

///用户： ninetailedfox
///时间： 2020/6/26
///邮箱： 1037438704@qq.com
///功能： 个人资料

class PersonalDataPage extends StatefulWidget {
  @override
  _PersonalDataPageState createState() => _PersonalDataPageState();
}

class _PersonalDataPageState extends State<PersonalDataPage> {
  DateTime initDateTime = DateTime.now();
  String imageUrl =
      "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1889057995,1262999376&fm=26&gp=0.jpg";
  TextEditingController textName = TextEditingController();
  TextEditingController bangongshijian = TextEditingController();
  TextEditingController shenfen = TextEditingController();

  Future getImage(index) async {
    if (index == 2) return;
    PickedFile pickedFile = await ImagePicker().getImage(
        source: index == 0 ? ImageSource.camera : ImageSource.gallery);
    File imageFile = File(pickedFile.path);
    //图片上传 获取链接
    DioUtils.getInstance().uploadFile(imageFile).then((value) {
      setState(() {
        imageUrl = value['file_url'] ?? "";
      });
    });
  }

  @override
  void initState() {
    super.initState();
    Map<String, dynamic> map = {
      "token": Constant.getToken(),
      "role": Constant.getRole()
    };
    DioUtils.getInstance().post(ApiService.userInfo, map, (successCallBack) {
      imageUrl = successCallBack["data"]["img"];
      SpUtil.putString("img", imageUrl);
      textName.text = successCallBack["data"]["name"];
      shenfen.text = Constant.getRole();
      setState(() {});
    }, (errorCallBack) {});
  }

  @override
  Widget build(BuildContext context) {
    MyAppViewModel myAppViewModel = Provider.of(context);
    getTime();
    ScreenUtil.instance = ScreenUtil(width: 1080, height: 1920)..init(context);
    return GestureDetector(
      onTap: () => FocusScope.of(context).requestFocus(FocusNode()),
      child: Scaffold(
        backgroundColor: Colours.gray_f6,
        appBar: MyAppBar2(title: "个人资料"),
        body: Column(
          children: <Widget>[
            Container(
              padding: EdgeInsets.only(
                right: ScreenUtil().setWidth(35),
                left: ScreenUtil().setWidth(35),
                top: ScreenUtil().setWidth(26),
                bottom: ScreenUtil().setWidth(26),
              ),
              margin:
                  EdgeInsets.only(top: ScreenUtil().setWidth(34), bottom: 1),
              color: Colors.white,
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Text("头像", style: TextStyles.textDark37),
                  Spacer(),
                  GestureDetector(
                    onTap: () {
                      PromptDialogWidgets(context).showaFileDialog(
                          getIndex: (index) {
                        getImage(index);
                      });
                    },
                    child: Container(
                      width: ScreenUtil().setWidth(101),
                      height: ScreenUtil().setWidth(101),
                      decoration: BoxDecoration(
                        color: Colors.greenAccent,
                        borderRadius: BorderRadius.circular(50),
                        image: DecorationImage(
                            image: NetworkImage(imageUrl), fit: BoxFit.cover),
                      ),
                    ),
                  ),
                ],
              ),
            ),
            RightEditWidget(
              textEditingController: textName,
              rightTitle: "昵称",
              leftTextStyle: TextStyles.textDark37,
            ),
            RightEditWidget(
              enabled: false,
              textEditingController: shenfen,
              rightTitle: "身份",
              leftTextStyle: TextStyles.textDark37,
            ),
            GestureDetector(
              child: Visibility(
                child: RightEditWidget(
                  enabled: false,
                  hintText: "请选择",
                  textEditingController: bangongshijian,
                  rightTitle: "办公时间",
                  leftTextStyle: TextStyles.textDark37,
                ),
                visible: myAppViewModel.identity,
              ),
              onTap: () {
                PromptDialogWidgets(context).dateButtomDialog(
                    dateTime: initDateTime,
                    onConfirm: (dateTime) {
                      initDateTime = dateTime;
                      getTime();
                      setState(() {});
                    });
              },
            ),
            Container(
              margin: EdgeInsets.only(
                top: ScreenUtil().setWidth(87),
                left: ScreenUtil().setWidth(134),
                right: ScreenUtil().setWidth(134),
              ),
              child: ButtonWidget().ellipseButtonWidget(
                  buttonName: "提交",
                  heightDouble: ScreenUtil().setWidth(130),
                  widthDouble: double.maxFinite,
                  textStyle: TextStyles.textWhite43,
                  onPressed: () {
                    Map<String, dynamic> map = Map();
                    map.putIfAbsent("token", () => Constant.getToken());
                    map.putIfAbsent("img", () => imageUrl);
                    if (textName.text != null || textName.text != "") {
                      map.putIfAbsent("name", () => textName.text);
                    }
                    if (initDateTime != null && myAppViewModel.identity) {
                      map.putIfAbsent("work_time",
                          () => initDateTime.millisecondsSinceEpoch);
                    }
                    DioUtils.getInstance().post(
                        myAppViewModel.identity
                            ? ApiService.uploadTeacher
                            : ApiService.updateParent,
                        map, (successCallBack) {
                      Navigator.pop(context);
                      myAppViewModel.refreshMyUser();
                    }, (errorCallBack) {});
                  }),
            )
          ],
        ),
      ),
    );
  }

  getTime() {
    bangongshijian.text =
        '${initDateTime.month.toString().padLeft(2, '0')}-${initDateTime.day.toString().padLeft(2, '0')}\t${initDateTime.hour.toString().padLeft(2, '0')}:${initDateTime.minute.toString().padLeft(2, '0')}';
  }
}
